package com.ktjiaoyu.server.config.security;

import com.ktjiaoyu.server.pojo.Menu;
import com.ktjiaoyu.server.pojo.Role;
import com.ktjiaoyu.server.service.IMenuService;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

/**
 * 权限控制
 * 用于获取访问本次url请求所需的角色权限
 * @Author JieGe
 * @Create 2022/3/4 - 23:58
 * @Description
 */
@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {

    @Resource
    private IMenuService menuService;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        // 1、获取请求的url
        String requestUrl = ((FilterInvocation)o).getRequestUrl();
        // 2、根据角色获取菜单列表
        List<Menu> menus = menuService.getMenusWithRole();
        for (Menu menu : menus) {
            // 判断请求中的url与menu中的url是否匹配
            if (antPathMatcher.match(menu.getUrl(), requestUrl)) {
                // 如果两个url是匹配的，把匹配得上的角色取出来赋值给String[] str角色名数组
                String[] str = menu.getRoles().stream().map(Role::getName).toArray(String[]::new);
                // 再把角色名数组通过createList()方法存放list中
                return org.springframework.security.access.SecurityConfig.createList(str);
            }
        }
        // 没匹配的url默认登录即可访问(默认给用户一个用于登录的角色)
        return org.springframework.security.access.SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
